package com.sphd.emanu.activity.materials;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;

import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.permission.Moudle;
import com.sphd.emanu.pojo.CategoryAndStorageEntity;
import com.sphd.emanu.pojo.goods.Category;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.pojo.material.Material;
import com.sphd.emanu.pojo.material.Storage;
import com.sphd.emanu.utils.PermissionConfig;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * todo 新增物料和修改物料
 *
 * @Author Hu
 * @Time 2017/6/8 -- 11:29.
 * @Email 87683202@qq.com
 */
public class MaterialsActivity extends MVPBaseActivity<MaterialsContract.View, MaterialsPresenter> implements MaterialsContract.View {

    @BindView(R.id.btn_edit_save)
    TextView btnEditSave;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.m_name)
    MaterialEditText mName;
    @BindView(R.id.m_specification)
    MaterialEditText mSpecification;
    @BindView(R.id.m_stock)
    MaterialEditText mStock;
    @BindView(R.id.m_category)
    TextView mCategory;
    @BindView(R.id.m_stock_min)
    MaterialEditText mStockMin;
    @BindView(R.id.m_Storage_location)
    TextView mStorageLocation;
    @BindView(R.id.layout_m_category)
    LinearLayout layoutMCategory;
    @BindView(R.id.layout_m_Storage_location)
    LinearLayout layoutMStorageLocation;
    Intent intent;
    Bundle bundle;
    Material material;
    User user;
    int flag = 0;
    int TYPE = 0;
    int cateId;
    int storageId = 0;
    private AndroidNextInputs inputs;
    CategoryAndStorageEntity categoryAndStorageEntity;
    Category category;
    String parentName;
    boolean isCanDo=false;
    List<Moudle> moudles;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_materials);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
    }


    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        moudles= (List<Moudle>) bundle.getSerializable(Constant.PERMISSION_LIST);
        isCanDo=isCanDo(moudles, PermissionConfig.MENU_STOREHOUSE_8);

        flag = bundle.getInt(Constant.FLAG);
        inputs = new AndroidNextInputs();
        inputs.add(mName, StaticScheme.Required().msgOnFail("必填项"), StaticScheme.NotBlank().msgOnFail("名称不能为空"));
        inputs.add(mSpecification, StaticScheme.Required().msgOnFail("必填项"), StaticScheme.NotBlank().msgOnFail("规格不能为空"));
        inputs.add(mStock, StaticScheme.Required().msgOnFail("必填项"), StaticScheme.NotBlank().msgOnFail("当前库存不能为空"), StaticScheme.Numeric().msgOnFail("当前库存只能为数值"));
        inputs.add(mStockMin, StaticScheme.Required().msgOnFail("必填项"), StaticScheme.NotBlank().msgOnFail("最低库存不能为空"), StaticScheme.Numeric().msgOnFail("最低库存只能为数值"));
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        parentName = bundle.getString(Constant.CATEGORY_PARENT_NAME);
        //如果是商品或者不能操作的人员 则隐藏保存按钮
        if (!isCanDo||parentName.equals("商品")){
            btnEditSave.setVisibility(View.GONE);
        }

        if (flag == 0) {
            TYPE = -1;
            setTitleBar(toolbar, "新增材料");
            btnEditSave.setText("保存");
            category = (Category) bundle.getSerializable(Constant.CATEGORY);
            mCategory.setText(category.getName());
            mCategory.setEnabled(false);
            layoutMCategory.setEnabled(false);
            cateId = category.getId();
            getList();
        } else {
            setTitleBar(toolbar, "编辑材料");
            material = (Material) bundle.getSerializable(Constant.MATERIAL);
            setTextAndShowClearBtn(mName, material.getName(), false, false);
            setTextAndShowClearBtn(mSpecification, material.getSpecifications(), false, false);
            setTextAndShowClearBtn(mStock, material.getStockInfo() != null ? String.valueOf(material.getStockInfo().getStock()) : "", false, false);
            mCategory.setText(material.getCategoryName());

            cateId = material.getCategory();
            if (material.getStorage() != null) {
                storageId = material.getStorage().getId();
            }
            setTextAndShowClearBtn(mStockMin, material.getStockInfo() != null ? String.valueOf(material.getStockInfo().getMinimumStock()) : "", false, false);
            mStorageLocation.setText(material.getStorage() != null ? (material.getStorage().getName() + "#") : "??#");

        }


    }

    private void getList() {
        showProgressDialog();
        mPresenter.categorAndStorage(user.getOid(), cateId);
    }

    private void setTextAndShowClearBtn(MaterialEditText tv, String s, boolean isShow, boolean enabled) {
        tv.setText(s);
        tv.setShowClearButton(isShow);
        tv.setEnabled(enabled);
    }

    @OnClick({R.id.btn_edit_save, R.id.layout_m_category, R.id.layout_m_Storage_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_edit_save:
                // TODO: 2017/6/2  如果type==0 则表示为要按钮由编辑转换的 要执行物料类型及库位list的获取
                if (TYPE == 0) {
                    getList();
                } else {
                    // TODO: 2017/6/2 type！=0 则是表示 保存按钮 只区分是新增还是编辑
                    if (inputs.test()) {
                        // TODO: 2017/6/2  flag==0 表示新增 ==1表示编辑
                        if (flag == 0) {
                            showProgressDialog();

                            mPresenter.addMaterial(mName.getText().toString().trim(),
                                    mSpecification.getText().toString().trim(), cateId, mStockMin.getText().toString().trim(),
                                    mStock.getText().toString().trim(),
                                    storageId == 0 ? null : storageId);
                        } else if (flag == 1) {
                            mPresenter.updateMaterial(material.getId(), mName.getText().toString().trim(),
                                    mSpecification.getText().toString().trim(), cateId, mStockMin.getText().toString().trim(),
                                    mStock.getText().toString().trim(),
                                    storageId == 0 ? null : storageId);

                        }
                    } else {
                        toast("请按照提示填写对应的内容");
                    }

                }
                break;
            case R.id.layout_m_category:
                if (categoryAndStorageEntity != null)
                    showList(categoryAndStorageEntity.getCategory(), 0);
                break;
            case R.id.layout_m_Storage_location:
                if (categoryAndStorageEntity != null)
                    showList(categoryAndStorageEntity.getStorage(), 1);
                break;
        }
    }

    private void showList(final List<?> list, final int type) {
        final String[] strings = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            strings[i] = (type == 0 ? (((Category) list.get(i)).getParentName() + "-" + ((Category) list.get(i)).getName()) : (((Storage) list.get(i)).getName()));
        }

        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle(type == 0 ? "请选择分类？" : "请选择库位？").
                setIcon(R.drawable.ic_launcher)
                .setItems(strings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (type == 0) {
                            cateId = ((Category) list.get(which)).getId();
                            mCategory.setText(((Category) list.get(which)).getName());
                        } else {
                            mStorageLocation.setText(strings[which]);
                            storageId = ((Storage) list.get(which)).getId();
                        }
                    }
                }).setNegativeButton("取消", null).
                        create();
        alertDialog.show();
    }

    @Override
    public void setEntity(CategoryAndStorageEntity categoryAndStorageEntity) {
        dissProgressDialog();
        this.categoryAndStorageEntity = categoryAndStorageEntity;
        if (flag == 0) {

//            cateId = categoryAndStorageEntity.getCategory().get(0).getId();
//            mCategory.setText(categoryAndStorageEntity.getCategory().get(0).getName());
        } else {
            if (parentName.equals("半成品") || parentName.equals("外购成品")){
                mName.setEnabled(false);
                mSpecification.setEnabled(false);
                mStockMin.setEnabled(false);
                mStock.setEnabled(false);
                layoutMStorageLocation.setEnabled(false);
                inputs.remove(mStockMin);
                inputs.remove(mStock);
            }else {
                mName.setEnabled(true);
                mName.setShowClearButton(true);
                mSpecification.setEnabled(true);
                mSpecification.setShowClearButton(true);
                mStock.setEnabled(true);
                mStock.setShowClearButton(true);
                mStockMin.setEnabled(true);
                mStockMin.setShowClearButton(true);
                mCategory.setEnabled(true);
                layoutMStorageLocation.setEnabled(true);
            }
            TYPE = 1;
            btnEditSave.setText("保存");
            dissProgressDialog();
        }
    }

    @Override
    public void setRes(int res) {
        dissProgressDialog();
        if (res == 1) {
            setResult(Constant.REQUEST_CODE);
            toast("操作成功");
            finish();
        } else {
            toast("操作失败，请重试。");
        }
    }
}
